<template>
  <div class="pagination mask">
    <div class="first p-btn block" v-show="first" @click="onButtonClick(1)">首页</div>
    <div class="p-btn block" v-show="current !== 1" @click="onButtonClick(prev)">上一页</div>
    <div
      class="p-btn block"
      v-for="(item,index) in pageList"
      :key="index"
      :class="{ current: item == current }"
      @click="onButtonClick(item)"
    >{{ item }}</div>
    <div class="p-btn block" v-show="current !== lastPage" @click="onButtonClick(next)">下一页</div>
    <div class="first p-btn block" v-show="last" @click="onButtonClick(lastPage)">尾页</div>
  </div>
</template>
<script>
import { reactive, toRefs } from '@vue/reactivity'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
export default {
  emits: ['changePage'],
  props: ['data'],
  setup(props, context) {
    const { first, last, maxpage, current, size, total } = props.data
    const state = reactive({
      first,
      last,
      maxpage,
      current,
      size,
      total,
      lastPage: 0,
      pageList: [],
      prev: 0,
      next: 0
    })
    onMounted(() => {
      const instance = getCurrentInstance()
      console.log(instance);
      state.first = state.first || false
      state.last = state.last || false
      state.maxpage = state.maxpage || 5
      state.lastPage = Math.ceil(state.total / state.size)
      reConfig()
    })
    const onButtonClick = (page) => {
      state.current = page
      reConfig()
    }
    

    function reConfig() {
      let start = Math.ceil(state.current - state.maxpage / 2)
      start = start < 1 ? 1 : start
      let end = start + state.maxpage - 1
      end = end > state.lastPage ? state.lastPage : end
      // console.log(start,end);
      let list = []
      for (let i = start; i <= end; i++) {
        list.push(i)
      }
      state.pageList = list
      state.prev = state.current - 1
      state.next = state.current + 1
    }

    return {
      ...toRefs(state),
      onButtonClick
    }
  },
}
</script>
<style lang="less" scoped>
@import "../../theme.less";
.pagination {
  user-select: none;
  display: flex;
  padding: 10px;
  border-radius: 8px;
  .p-btn {
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    border: 1px solid @theme-line;
    margin: 0 2px;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.3);
    transform: scale(1.1);
    box-shadow: 0 0 4px 2px @theme-line;
  }
}
</style>